package com.cwits.wifi.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity;
import com.cwits.wifi.base.baseinterface.IBaseActivity;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.prapi.ProjectAPI;
import com.cwits.wifi.tool.DeviceUuidFactory;
import com.cwits.wifi.ui.dialog.OneDialog;
import com.cwits.wifi.ui.fragment.FileFragment;
import com.cwits.wifi.ui.fragment.IndexFragment;
import com.cwits.wifi.ui.fragment.LeftFragment;
import com.cwits.wifi.ui.service.CommunicationService;
import com.cwits.wifi.ui.service.EncodeAVIToMP4Service;
import com.cwits.wifi.ui.view.CustomViewPager;
import com.cwits.wifi.update.UpDateTool;
import com.cwits.wifi.update.UpdateChecker;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.PreferencesHelper;
import com.jieli.lib.stream.tools.CommandHub;
import com.jieli.lib.stream.util.ICommon;
import com.nineoldandroids.view.ViewHelper;
import com.tencent.bugly.beta.Beta;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * Created by ZhangHua on 16-03-01.
 */
public class MainActivity extends BaseActivity implements UpdateChecker.IUpdateCheckerListener, IBaseActivity, OnItemClickListener, ICommon, View.OnClickListener {
    private final String tag = getClass().getSimpleName();
    private AlertView mAlertView;

    private CustomViewPager mViewPager;
    private List<Fragment> mTabs = new ArrayList<Fragment>();
    private FragmentPagerAdapter mAdapter;
    public static boolean CLEAN_SOS;
    public static boolean CLEAN_ALL;
    private TextView mTvIndex, mTvFile, mTitle, mZoomIn_fill_view, mZoomOut_fill_view, mTvSelect;
    private ImageView mImIndex, mImFile, mLeftImage, mRightImage, mLeftMSMMark;
    private RelativeLayout mRlIndex, mRlFile, mRlTile, mDrag_fill, mZoomOut_fill, mZoonIn_fill, mDrag_fill_rl;
    private LinearLayout mLaunch_linearbottom;
    private DrawerLayout mDrawerLayout;
    private View mLeft_View, mRight_View;
    private boolean mIsCanGo = true;
    private OneDialog updateDialog;
    private ProgressDialog mProgressDialog;
    private AlertDialog installDialog;
    private boolean mNeedUpdateFireware = false;

    private final int CODE_OAUTH = 1;
    private final int CODE_USERINFO = 2;
    private final int CODE_SOFT_VERSIONINFO = 3;
    private final int CODE_APP_VERSIONINFO = 4;
    private final int CODE_PENGCIINFO = 5;
    private String mToken = "";
    private Handler mHandler;

    private OneDialog oneDialog;
    //private boolean mIsCheckUpdate = false;
    ProjectAPI api;
    /*lihaoran: register push message broadcastReceiver start*/
    private MainActivityPushMSMReceiver mPushMSMReceiver;
    /*lihaoran: register push message broadcastReceiver end*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 设置屏幕常亮
        setContentView(R.layout.activity_launcher);
        mHandler = new Handler();
        /*lihaoran: register push message broadcastReceiver start*/
        mPushMSMReceiver = new MainActivityPushMSMReceiver();

        IntentFilter filter = new IntentFilter();
        filter.addAction("com.cwits.wifi.receive.pushmsm");
        registerReceiver(mPushMSMReceiver, filter);
        /*lihaoran: register push message broadcastReceiver end*/

        CLEAN_SOS = false;
        intiView();
        initEvents();

        initData();

        mViewPager.setOverScrollMode(ViewPager.OVER_SCROLL_NEVER);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setNoScroll(true);
        api = new ProjectAPI();
        autoCheckUpdate();

        //启动后台检测，判断是否需要对app或是设备固件升级
        //showProcessDialog();
        api.getOauth(this, new DeviceUuidFactory(this.getApplicationContext()).getDeviceUuid().toString(), CODE_OAUTH);
        if (PreferencesHelper.getSharedPreferences(this.getApplication()).getString("device_id", "").equals("") == false)
            api.getPengciInfo(this, 2, PreferencesHelper.getSharedPreferences(this.getApplication()).getString("device_id", ""), CODE_PENGCIINFO);
        //startService(new Intent(this.getApplicationContext(), EncodeAVIToMP4Service.class));
        //EncodeAVIToMP4Service.getInstance();
        //InputStream inStream = new FileInputStream("");
        startService(new Intent(MainApplication.getApplication(), EncodeAVIToMP4Service.class));

        Beta.checkUpgrade();
    }

    public boolean getIsCanGo() {
        return mIsCanGo;
    }

    /**
     * 初始化view
     */
    private void intiView() {
        mZoomOut_fill_view = (TextView) findViewById(R.id.zoomout_fill_view);
        mZoomIn_fill_view = (TextView) findViewById(R.id.zoomin_fill_view);
        mDrag_fill_rl = (RelativeLayout) findViewById(R.id.drag_fill_rl);
        initDragAndZoom();
        mRlTile = (RelativeLayout) findViewById(R.id.index_rl_win);
        mDrag_fill = (RelativeLayout) findViewById(R.id.drag_fill);
        mZoonIn_fill = (RelativeLayout) findViewById(R.id.zoomin_fill);
        mZoomOut_fill = (RelativeLayout) findViewById(R.id.zoomout_fill);
        mLaunch_linearbottom = (LinearLayout) findViewById(R.id.launch_linearbottom);
        mTitle = (TextView) findViewById(R.id.titile_text);
        mLeftImage = (ImageView) findViewById(R.id.left_imageview);
        mRightImage = (ImageView) findViewById(R.id.right_imageview);
        mLeftMSMMark = (ImageView) findViewById(R.id.left_pushmsm_mark);
        //mLeftMSMMark.setVisibility(View.VISIBLE);
        mTvFile = (TextView) findViewById(R.id.launch_tv_file);
        mTvIndex = (TextView) findViewById(R.id.launch_tv_index);
        mTvSelect = (TextView) findViewById(R.id.launch_tv_select);
        mImFile = (ImageView) findViewById(R.id.launch_im_file);
        mImIndex = (ImageView) findViewById(R.id.launch_im_index);
        mRlFile = (RelativeLayout) findViewById(R.id.launch_rl_file);
        mRlIndex = (RelativeLayout) findViewById(R.id.launch_rl_index);
        mViewPager = (CustomViewPager) findViewById(R.id.launch_viewpager);

        mDrag_fill.setOnClickListener(this);
        mZoonIn_fill.setOnClickListener(this);
        mZoomOut_fill.setOnClickListener(this);
        mLeftImage.setOnClickListener(this);
        mRightImage.setOnClickListener(this);
        mTvSelect.setOnClickListener(this);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerLayout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mLeft_View = (View) findViewById(R.id.left_drawer);
        mRight_View = (View) findViewById(R.id.right_drawer);

        Locale locale = getResources().getConfiguration().locale;
        if (locale.getLanguage().endsWith("zh")) {
            mLeftMSMMark.setVisibility(View.VISIBLE);
        } else {
            mLeftMSMMark.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onItemClick(Object o, int i) {
        super.onItemClick(o, i);
    }

    private void initDragAndZoom() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        System.out.print(width + "----" + height);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(

                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);


        params.height = width * 3 / 4;

        params.width = width;

        //mSurfaceView.setWidthAndHeight(width,width*9/16);
        mZoomOut_fill_view.setLayoutParams(params);
        mZoomIn_fill_view.setLayoutParams(params);
        mDrag_fill_rl.setLayoutParams(params);
    }

    /*
     * 定义viewpager
     */
    private void initData() {
        IndexFragment tabFragment1 = new IndexFragment();
        Bundle args = new Bundle();
        args.putString("title", "First Fragment!");
        tabFragment1.setArguments(args);

        FileFragment tabFragment2 = new FileFragment();
        Bundle args2 = new Bundle();
        args2.putString("title", "First2 Fragment!");
        tabFragment2.setArguments(args2);

        mTabs.add(tabFragment1);
        mTabs.add(tabFragment2);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mTabs.size();
            }

            // 初始化每个页卡选项
            @Override
            public Object instantiateItem(ViewGroup arg0, int position) {

                Fragment ff = (Fragment) super.instantiateItem(arg0, position);
                // ff.setThings(mTabs.get(position).getr,position);
                return ff;
            }

            @Override
            public Fragment getItem(int arg0) {
                return mTabs.get(arg0);
            }
        };

        mRlIndex.setOnClickListener(this);
        mRlFile.setOnClickListener(this);

    }

    public void selectAllT() {
        mTvSelect.setText(R.string.operation_choice);
    }

    public void selectAllF() {
        mTvSelect.setText(R.string.operation_cancel);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // land do nothing is ok
            // super.setTranslucen(R.color.default_title_color);
            //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mLaunch_linearbottom.setVisibility(View.GONE);
            mRlTile.setVisibility(View.GONE);
            mRlFile.setVisibility(View.GONE);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // port do nothing is ok
            /*
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            super.setTranslucen();
            */
            mLaunch_linearbottom.setVisibility(View.VISIBLE);
            mRlTile.setVisibility(View.VISIBLE);
            mRlFile.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.launch_tv_select:
                if (mTabs.get(1) instanceof FileFragment) {
                    ((FileFragment) (mTabs.get(1))).selectAll();
                }

                break;

            case R.id.drag_fill:
                mDrag_fill.setVisibility(View.GONE);
                mZoomOut_fill.setVisibility(View.VISIBLE);
                if (mTabs.get(0) instanceof IndexFragment) {
                    ((IndexFragment) (mTabs.get(0))).displayScalePanel();
                }
                break;
            case R.id.zoomout_fill:
                mZoomOut_fill.setVisibility(View.GONE);
                mZoonIn_fill.setVisibility(View.VISIBLE);
                break;
            case R.id.zoomin_fill:
                mZoonIn_fill.setVisibility(View.GONE);
                break;
            case R.id.launch_rl_index:
                if (mViewPager.getCurrentItem() == 0)
                    return;
                if (mApplication.getIsOffLineMode() && mApplication.getIsNeedReconnect()) {
                    connectDevice(mConnectingSSID, mPassWord);
                }
                mTvIndex.setTextColor(getResources().getColor(R.color.index_text_select));
                mTvFile.setTextColor(getResources().getColor(R.color.index_text_normal));
                mImIndex.setImageResource(R.mipmap.icon_home_selected);
                mImFile.setImageResource(R.mipmap.icon_load_normal);
                mViewPager.setCurrentItem(0, false);
                mTitle.setText(R.string.app_title);
                mLeftImage.setVisibility(View.VISIBLE);
//                mRightImage.setVisibility(View.VISIBLE);
                mTvSelect.setVisibility(View.GONE);
                //mLeftMSMMark.setVisibility(View.VISIBLE);
                Locale locale = getResources().getConfiguration().locale;
                if (locale.getLanguage().endsWith("zh")) {
                    mLeftMSMMark.setVisibility(View.VISIBLE);
                } else {
                    mLeftMSMMark.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.launch_rl_file:
                if (mViewPager.getCurrentItem() == 1)
                    return;
                if (mTabs.get(0) instanceof IndexFragment) {
                    IndexFragment inf = ((IndexFragment) (mTabs.get(0)));
                    if (inf.getIsEncording() || inf.getIsRecording()) {
                        showVideoCloseDialog(1);
                        return;
                    }
                }
                mLeftMSMMark.setVisibility(View.INVISIBLE);
                mTvIndex.setTextColor(getResources().getColor(R.color.index_text_normal));
                mTvFile.setTextColor(getResources().getColor(R.color.index_text_select));
                mImIndex.setImageResource(R.mipmap.icon_home_normal2);
                mImFile.setImageResource(R.mipmap.icon_load_selected);
                mViewPager.setCurrentItem(1, false);
                mTitle.setText(R.string.app_downLoaded);
                mLeftImage.setVisibility(View.VISIBLE);
                mRightImage.setVisibility(View.VISIBLE);
//                mTvSelect.setVisibility(View.VISIBLE);
                mTvSelect.setText(R.string.operation_choice);
                if (mTabs.get(1) instanceof FileFragment) {
                    ((FileFragment) (mTabs.get(1))).initSelectAllCheckBox();
                }
                break;
            case R.id.left_imageview:
                if (mTabs.get(0) instanceof IndexFragment) {
                    IndexFragment inf = ((IndexFragment) (mTabs.get(0)));
                    if (inf.getIsEncording() || inf.getIsRecording()) {
                        showVideoCloseDialog(2);
                        return;
                    }
                }
                if (mDrawerLayout.isDrawerOpen(mLeft_View)) {
                    mDrawerLayout.closeDrawer(mLeft_View);
                } else {
                    mDrawerLayout.openDrawer(mLeft_View);
                }
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                break;
            case R.id.right_imageview:
//                if (mTabs.get(0) instanceof IndexFragment) {
//                    IndexFragment inf = ((IndexFragment) (mTabs.get(0)));
//                    if (inf.getIsEncording() || inf.getIsRecording()) {
//                        showVideoCloseDialog(3);
//                        return;
//                    }
//                }
//                if (mDrawerLayout.isDrawerOpen(mRight_View)) {
//                    mDrawerLayout.closeDrawer(mRight_View);
//                } else {
//                    mDrawerLayout.openDrawer(mRight_View);
//                }
//                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                Intent traceIntent = new Intent(getApplicationContext(), MyInfoActivity.class);
                traceIntent.putExtra("url", "http://uat-api.4s12580.com/H5/wxpage/tracks/playback.aspx?objectid=201413979&from=singlemessage&isappinstalled=0");
                traceIntent.putExtra("title", getResources().getString(R.string.trace_info));
                startActivity(traceIntent);
                break;
            default:
                break;
        }

    }

    @Override
    public void onWiFiState(boolean isAutoDisable, int state) {
        switch (state) {
            case 2:
                mHandler.removeCallbacks(msRunnable);
                break;
        }
    }

    /**
     * 父类回调接口，通知子界面此时已经连接成功
     */
    @Override
    public void displayVideo() {
        if (mTabs.get(0) instanceof IndexFragment) {
            ((IndexFragment) (mTabs.get(0))).displayVideo();
        }
        mHandler.removeCallbacks(msRunnable);
        mHandler.post(msRunnable);
        //判断是否需要固件更新，是否已下载，然后上传到设备，最后重启设备
        //new Thread(uploadFTPServer).start();
    }

    private Runnable msRunnable = new Runnable() {
        @Override
        public void run() {
            //CommandHub.getInstance().requestStatus(CTP_ID_DEFAULT, "0600");
            CommandHub.getInstance().requestStatus("2", "0600");
            Dbug.i(tag, "-------" + "已发送命令：" + "0600");
            mHandler.postDelayed(msRunnable, 60 * 1000);
        }
    };


    private void initEvents() {
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerStateChanged(int newState) {
                if (mTabs.get(0) instanceof IndexFragment) {
                    IndexFragment inf = ((IndexFragment) (mTabs.get(0)));
                    if (inf.getIsEncording() || inf.getIsRecording()) {
                        mIsCanGo = false;
                    } else {
                        mIsCanGo = true;
                    }
                }
                Dbug.i(tag, "-----------onDrawerStateChanged----------------" + newState);
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                Dbug.i(tag, "-----------onDrawerSlide----------------" + slideOffset);
                if (mTabs.get(0) instanceof IndexFragment) {
                    IndexFragment inf = ((IndexFragment) (mTabs.get(0)));
                    if (inf.getIsEncording() || inf.getIsRecording()) {
                        mDrawerLayout.closeDrawer(mLeft_View);
                        mDrawerLayout.closeDrawer(mRight_View);
                    }
                }

                if (mTabs.get(0) instanceof IndexFragment) {
                    IndexFragment inf = ((IndexFragment) (mTabs.get(0)));
                    if (inf.getIsEncording() || inf.getIsRecording()) {
                        mIsCanGo = false;
                    } else {
                        mIsCanGo = true;
                    }
                }
                View mContent = mDrawerLayout.getChildAt(0);
                View mMenu = drawerView;
                float scale = 1 - slideOffset;
                float rightScale = 0.8f + scale * 0.2f;

                if (drawerView.getTag().equals("LEFT")) {

                    float leftScale = 1 - 0.3f * scale;

                    //ViewHelper.setScaleX(mMenu, leftScale);
                    //ViewHelper.setScaleY(mMenu, leftScale);
                    ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
                    ViewHelper.setTranslationX(mContent, mMenu.getMeasuredWidth() * (1 - scale));
                    //ViewHelper.setPivotX(mContent, 0);
                    //ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
                    //ViewHelper.setScaleX(mContent, rightScale);
                    //ViewHelper.setScaleY(mContent, rightScale);
                } else {
                    ViewHelper.setTranslationX(mContent, -mMenu.getMeasuredWidth() * slideOffset);
                    // ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
                    // ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
                    //ViewHelper.setScaleX(mContent, rightScale);
                    // ViewHelper.setScaleY(mContent, rightScale);
                }

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                Dbug.i(tag, "-----------onDrawerOpened----------------");
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                Dbug.i(tag, "-----------onDrawerClosed----------------");
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                if (mApplication.getIsOffLineMode() && mApplication.getIsNeedReconnect()) {
                    connectDevice(mConnectingSSID, mPassWord);
                }
            }
        });
    }

    public static void delete(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }
            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }

    @Override
    public void onBackPressed() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (mTabs.get(0) instanceof IndexFragment) {
                ((IndexFragment) (mTabs.get(0))).toVertical();
            }
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            String message = getString(R.string.whether_exit_app);
            mAlertView = new AlertView(getString(R.string.dialog_tip), message,
                    getString(R.string.cancel), new String[]{getString(R.string.confirm)},
                    null, this, AlertView.Style.Alert, alertViewOnItemClickListener);
            mAlertView.setCancelable(true);
            mAlertView.show();
        }
    }

    private OnItemClickListener alertViewOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(Object o, int i) {
//            Dbug.d(tag, "onItemClick: "+i);
            switch (i) {
                case -1://cancel
                    mAlertView.dismiss();
                    break;
                case 0://exit APP
                    mAlertView.dismiss();
                    String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
                    Dbug.d(tag, "recordState:" + recordState);
                    if (ARGS_IN_RECORDING.equals(recordState)) {
                        //CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                        stopService(new Intent(MainApplication.getApplication(), EncodeAVIToMP4Service.class));
                        release();
                    } else {
                        stopService(new Intent(MainApplication.getApplication(), EncodeAVIToMP4Service.class));
                        release();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        /*lihaoran: change mark View status by Push message start*/
        setViewByPushMSM();
        if (mViewPager.getCurrentItem() == 1)
            mLeftMSMMark.setVisibility(View.INVISIBLE);
        /*lihaoran: change mark View status by Push message end*/

        /*
        if (mApplication.getIsOffLineMode() && mApplication.getIsNeedReconnect()) {
            connectDevice(mConnectingSSID, mPassWord);
        }
        */
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void refresh(Object... param) {
        //super.refresh(param);
        if (isTimeOut)//网络延迟
            return;
        int flag = ((Integer) param[0]).intValue();
        switch (flag) {
            case CODE_OAUTH://获取token码
                if (param.length > 0 && param[1] != null && param[1] instanceof String) {
                    String content = param[1].toString();
                    JSONObject json;
                    try {
                        json = new JSONObject(content);
                        String error = json.getString("error");
                        if (error.equals("0")) {
                            JSONObject data = json.getJSONObject("data");
                            mToken = data.getString("token");
                            String user_id = new DeviceUuidFactory(this.getApplicationContext()).getDeviceUuid().toString();
                            String soft_id = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("soft_id", "xxx");
                            String cid = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("cid", "xxx");
                            String ter_id = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("device_id", "xxx");
                            //if(cid.equals("xxx") == false&&ter_id.equals("xxx") == false&&soft_id.equals("xxx") == false)
                            api.getUpdateMobileRecord(this, mToken, user_id, getAppVersionName(), soft_id, ter_id, cid, CODE_USERINFO);
                            if (PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getBoolean("user_id_upload", false)) {
                                api.getSoftVersionInfo(this, mToken, user_id, ter_id, soft_id, CODE_SOFT_VERSIONINFO);
                                api.getAPPVersionInfo(this, mToken, user_id, getAppVersionName(), CODE_APP_VERSIONINFO);
                            }


                        }
                    } catch (JSONException e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
                break;
            case CODE_USERINFO://用户信息接收
                if (param.length > 0 && param[1] != null && param[1] instanceof String) {
                    String content = param[1].toString();
                    JSONObject json;
                    try {
                        json = new JSONObject(content);
                        String error = json.getString("error");
                        if (error.equals("0")) {
                            PreferencesHelper.putBooleanValue(this.getApplicationContext(), "user_id_upload", true);
                            /*
                            api.getVersionInfoOnService(this, mToken, new DeviceUuidFactory(this.getApplicationContext()).getDeviceUuid().toString(),
                                    getAppVersionName(),
                                    PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("soft_id", "xxx"),
                                    CODE_VERSIONINFO);
                            */
                        } else {
                            Dbug.i(tag, "-----CODE_USERINFO-----error:" + error);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CODE_SOFT_VERSIONINFO://固件版本接收
                if (param.length > 0 && param[1] != null && param[1] instanceof String) {
                    String content = param[1].toString();
                    JSONObject json;
                    try {
                        json = new JSONObject(content);
                        String error = json.getString("error");
                        if (error.equals("0")) {
                            //JSONObject data = json.getJSONObject("data");
                            String soft_id = json.optString("soft_id");
                            String soft_url = json.optString("soft_url");
                            String soft_size = json.optString("soft_size");
                            String soft_hash = json.optString("soft_hash");
                            //判断需要更新的东西
                            if (soft_id.equals("") == false && soft_id.equals(PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("downLoad_soft_id", "xxx")) == false
                                    && PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("soft_id", "xxx").equals("xxx") == false) {
                                //马上弹出提示框去下载
                                showIsUpdateDialog(soft_url, soft_id, soft_size, soft_hash);
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CODE_APP_VERSIONINFO://app版本更新接收
                if (param.length > 0 && param[1] != null && param[1] instanceof String) {
                    String content = param[1].toString();
                    JSONObject json;
                    try {
                        json = new JSONObject(content);
                        String error = json.getString("error");
                        if (error.equals("0")) {
                            //JSONObject data = json.getJSONObject("data");
                            String app_id = json.optString("app_id");
                            String app_url = json.optString("app_url");
                            String app_size = json.optString("app_size");
                            String app_hash = json.optString("app_hash");
                            //判断需要更新的东西
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;

            case CODE_PENGCIINFO:
                if (param.length > 0 && param[1] != null && param[1] instanceof String) {
                    String content = param[1].toString();
                    JSONObject json;
                    try {
                        json = new JSONObject(content);
                        boolean successed = json.getBoolean("Successed");
                        if (successed) {
                            Dbug.i("CODE_PENGCIINFO", "----successed--" + successed);
                            mApplication.setIsRegisterPengci(true);
                            LeftFragment leftFragment = (LeftFragment) getSupportFragmentManager().findFragmentByTag("LEFT");
                            leftFragment.displayNoPengciCilcle();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;

            case BaseActivity.ERROR:
                //Toast.makeText(this, "网络中断,请稍后操作！", Toast.LENGTH_SHORT).show();
                break;
            case BaseActivity.COOKIE_INVILD:
                Toast.makeText(this, "登陆过期!!", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onDownloadSoft(final boolean is_sucess, final String path_name, final String file_name) {
        if (is_sucess) {
            PreferencesHelper.putStringValue(this.getApplicationContext(), "downLoad_soft_id", file_name);
            PreferencesHelper.putStringValue(this.getApplicationContext(), "downLoad_soft_path", path_name);
        }
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                if (mProgressDialog != null && mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
                if (is_sucess) {
                    //固件下载成功
                    showToast(getString(R.string.firmware_download_success));
                } else {
                    //固件下载失败
                    showToast(getString(R.string.firmware_download_fail));
                }
            }
        });

    }

    private boolean IsDownLoadLatestSoft(String current_soft) {
        boolean flag = false;
        if (current_soft.equals(PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("downLoad_sodt_id", "xxx"))
                || current_soft.equals(""))
            flag = true;
        return flag;
    }

    private String getAppVersionName() {
        try {
            String pkName = this.getPackageName();
            String versionName = this.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            return versionName;
        } catch (Exception e) {
        }
        return null;
    }

    public void uploadSoft() {
        //固件上传升级
        String download_path = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("downLoad_soft_path", "xxx");
        if (!download_path.equals("xxx")) {
            showInstallDialog();
        }
    }

    /**
     * app版本更新检查接口
     */
    private void autoCheckUpdate() {

        long checkedTime = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getLong(UpdateChecker.UPDATE_CHECKED_DAY_KEY, 0L);

        long currTime = System.currentTimeMillis();

        if ((currTime - checkedTime < 3 * 60 * 60 * 1000)) {
            return;

        } else {
            //showProcessDialog("版本检查中...");
            resetTimeOutStatus();
            checkNetTimeOut();
            // �����°汾���
            UpdateChecker checker = new UpdateChecker(this);
            checker.addUpdateCheckerListener(this);
            checker.execute(new URL[0]);
            PreferencesHelper.putLongValue(this.getApplicationContext(), UpdateChecker.UPDATE_CHECKED_DAY_KEY,
                    currTime);
        }

    }


    @Override
    public void onUpdateCheckResult(boolean needUpdate, UpdateChecker.AppVersionInfo verInfo) {
        // TODO Auto-generated method stub
        if (isTimeOut)//网络延迟
            return;
        hideProgressDialog();
        if (null == verInfo) {
            return;
        }
        String version = verInfo.mVersionURL;

        final String str = version;
        if (needUpdate) {

            String message = "";
            try {
                String path = Environment.getExternalStorageDirectory()
                        .getAbsolutePath()
                        + "/lipeibao/168cardev/"
                        + "VersionFiles/"
                        + "cwcex_version_desc_"
                        + String.valueOf(verInfo.mVersionCode) + ".xml";
                File file = new File(path);

                if (file.exists()) {

                    InputStream in = new FileInputStream(file);

                    HashMap<String, String> map = UpDateTool.parse(in);
                    String key = Locale.getDefault().getLanguage() + "_"
                            + Locale.getDefault().getCountry();
                    if (map.containsKey(key)) {
                        message = map.get(key);
                    } else {
                        // 默认提示中文信息
                        if (map.containsKey("en_US")) {
                            message = map.get("en_US");
                        } else {
                            message = map.get(getString(R.string.version_update));
                        }
                    }
                } else {
                    message = getString(R.string.update_remind);

                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setCancelable(false);
            // final Dialog builder = new Dialog(getApplicationContext());
            View view = View.inflate(getApplicationContext(),
                    R.layout.dialog_update, null);
            TextView remind = (TextView) view
                    .findViewById(R.id.dialog_up_title);
            TextView msg_info = (TextView) view
                    .findViewById(R.id.dialog_up_msg);
            TextView textview_cancle = (TextView) view
                    .findViewById(R.id.dialog_up_canale);
            TextView textview_ok = (TextView) view
                    .findViewById(R.id.dialog_up_ok);
            //remind.setText(getString(R.string.update) + verInfo.mVersionName);
            // msg_info.setText(R.string.update_remind);
            msg_info.setText(message);
            textview_ok.setText(R.string.download_now);
            textview_cancle.setText(R.string.download_cancle);
            // RelativeLayout cancleRl = (RelativeLayout) view
            // .findViewById(R.id.dialog_del_ok);
            // RelativeLayout okRl = (RelativeLayout) view
            // .findViewById(R.id.dialog_del_cancle);

            builder.setView(view);

            final AlertDialog dialog = builder.create();

            textview_ok.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    dialog.dismiss();
                    if (null != str) {
                        Uri url = Uri.parse(str);
                        Intent intent = new Intent(Intent.ACTION_VIEW, url);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MainActivity.this.startActivity(intent);
                    } else {
                        Toast.makeText(MainActivity.this,
                                getString(R.string.download_failed),
                                Toast.LENGTH_SHORT).show();
                        finish();
                    }

                }
            });

            textview_cancle.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setView(view, 0, 0, 0, 0);
            dialog.show();
        }


    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mPushMSMReceiver);
        mHandler.removeCallbacks(msRunnable);
        super.onDestroy();
    }

    @Override
    public void onOptionsMenuClosed(Menu menu) {
        super.onOptionsMenuClosed(menu);
    }

    class MainActivityPushMSMReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            setViewByPushMSM();
            //System.out.println("PushMSM");
        }
    }

    @Override
    public void onPanelClosed(int featureId, Menu menu) {
        super.onPanelClosed(featureId, menu);
    }

    private void setViewByPushMSM() {
        int msmCount = PreferencesHelper.getSharedPreferences(MainActivity.this).getInt("PushMSMCount", 0);
        if (msmCount == 0) {
            mLeftMSMMark.setVisibility(View.VISIBLE);
        } else {
            mLeftMSMMark.setVisibility(View.VISIBLE);
        }

        Locale locale = getResources().getConfiguration().locale;
        if (locale.getLanguage().endsWith("zh")) {
            mLeftMSMMark.setVisibility(View.VISIBLE);
        } else {
            mLeftMSMMark.setVisibility(View.INVISIBLE);
        }
        LeftFragment leftFragment = (LeftFragment) getSupportFragmentManager().findFragmentByTag("LEFT");
        leftFragment.setFirstTitleLeftView(msmCount);
    }

    private static final String INSIDE_FTP_HOST_NAME = "192.168.1.1";
    private static final String INSIDE_FTP_USER_NAME = "FTPX";
    private static final String INSIDE_FTP_PASSWORD = "12345678";
    private final Runnable uploadFTPServer = new Runnable() {
        @Override
        public void run() {
            connectFTP(INSIDE_FTP_HOST_NAME, 21, INSIDE_FTP_USER_NAME, INSIDE_FTP_PASSWORD);
        }
    };

    /**
     * connect FTP,上传最新固件升级
     */
    private void connectFTP(String add, int port, String name, String paw) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        boolean isupload = false;
        FTPClient mFTPClient = new FTPClient();
        mFTPClient.setControlEncoding("GBK");
        mFTPClient.setDefaultPort(port);
        try {
            mFTPClient.connect(add);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
            try {
                if (mFTPClient.login(name, paw)) {


                    InputStream bis = new FileInputStream(PreferencesHelper.getSharedPreferences(MainActivity.this).getString("downLoad_soft_path", "xxx"));
                    mFTPClient.enterLocalPassiveMode();
                    mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                    mFTPClient.setBufferSize(1024 * 1024 * 5); //5M
                    //boolean issucess = mFTPClient.deleteFile("JL_AC51.txt");

                    if (mFTPClient.storeFile("JL_AC51.bfu", bis)) {
                        isupload = true;
                        Dbug.d(tag, "upload file success!");
                    } else {
                        Dbug.e(tag, "upload file failed!");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (mFTPClient.isConnected()) {
                    try {
                        mFTPClient.disconnect();
                        //Dbug.d(tag, "FTPClient is disconnected success!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            Dbug.w(tag, "Reply code is not a positive completion response.");
        }
        if (isupload) {
            String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
            if (ARGS_IN_RECORDING.equals(recordState)) {
                mNeedUpdateFireware = true;
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                try {
                    Thread.sleep(8000);
                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RESTART_DEVICE, ARGS_RESTART_DEVICE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } else {
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RESTART_DEVICE, ARGS_RESTART_DEVICE);
            }

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mProgressDialog != null && mProgressDialog.isShowing())
                        mProgressDialog.dismiss();
                    clearAllInfo();
                }
            }, 2000);
        }

    }


    private void clearAllInfo() {
        disconnectDevice();
    }

    /**
     * 下载更新信息
     *
     * @param download_soft_url
     */
    private boolean downloadVersionInfoFile(String download_soft_url) {
        URL url;
        HttpURLConnection connVerDesc = null;
        File verDescFilePath = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath()
                + "/com.cwits.wifi/"
                + "VersionFiles/");
        boolean result = false;

        try {
            if (!verDescFilePath.exists())
                verDescFilePath.mkdirs();
            File verDescFile = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath()
                    + "/com.cwits.wifi/"
                    + "VersionFiles/" + "JL_AC51.bfu");
            if (verDescFile.exists())
                verDescFile.delete();
            url = new URL(download_soft_url);
            connVerDesc = (HttpURLConnection) url.openConnection();
            if (connVerDesc != null && !connVerDesc.equals("")) {
                InputStream inVerDesc = new BufferedInputStream(
                        connVerDesc.getInputStream());
                OutputStream outFile = new BufferedOutputStream(
                        new FileOutputStream(verDescFile));

                byte b = 0;
                while ((b = (byte) inVerDesc.read()) != -1) {
                    outFile.write(b);
                }

                inVerDesc.close();
                outFile.close();

                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != connVerDesc)
                connVerDesc.disconnect();
        }

        return result;
    }

    private void showVideoCloseDialog(final int whichItem) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(this, R.layout.dialog_video_close_two_btn,
                null);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_video_close_rl_cancle);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_video_close_rl_ok);

        builder.setView(view);

        final AlertDialog dialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                /*
                if (mTabs.get(0) instanceof IndexFragment) {
                    ((IndexFragment) (mTabs.get(0))).videoOpenOrClose();
                }
*/
                switch (whichItem) {
                    //对不同的控件做出不同的响应
                    case 1:
                        mTvIndex.setTextColor(getResources().getColor(R.color.index_text_normal));
                        mTvFile.setTextColor(getResources().getColor(R.color.index_text_select));
                        mImIndex.setImageResource(R.mipmap.icon_home_normal2);
                        mImFile.setImageResource(R.mipmap.icon_load_selected);
                        mViewPager.setCurrentItem(1, false);
                        mTitle.setText(R.string.app_downLoaded);
                        mLeftImage.setVisibility(View.VISIBLE);
                        mRightImage.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        if (mDrawerLayout.isDrawerOpen(mLeft_View)) {
                            mDrawerLayout.closeDrawer(mLeft_View);
                        } else {
                            mDrawerLayout.openDrawer(mLeft_View);
                        }
                        break;
                    case 3:
                        if (mDrawerLayout.isDrawerOpen(mRight_View)) {
                            mDrawerLayout.closeDrawer(mRight_View);
                        } else {
                            mDrawerLayout.openDrawer(mRight_View);
                        }
                        break;
                }
                dialog.dismiss();


            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        builder.setCancelable(false);
    }

    /**
     * 下载成功是否安装dialog
     */
    private void showInstallDialog() {

        oneDialog = new OneDialog(MainActivity.this, getString(R.string.firmware_update), upListener);
        oneDialog.show();

        /*
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(this, R.layout.dialog_update_one_btn,
                null);
        TextView tvText = (TextView) view.findViewById(R.id.dialog_update_one_tv);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_update_one_rl);
        builder.setView(view);

        installDialog = builder.create();
        installDialog.setCanceledOnTouchOutside(false);
        installDialog.setCancelable(false);
        tvText.setText("固件升级！");
        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new Thread(uploadFTPServer).start();
                installDialog.dismiss();
                showProgress("固件正在上传到记录仪，请稍后！");
            }
        });

        installDialog.setView(view, 0, 0, 0, 0);
        installDialog.show();
        builder.setCancelable(false);
        */
    }

    private View.OnClickListener upListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_update_one_rl:

                    oneDialog.dismiss();
                    new Thread(uploadFTPServer).start();
                    showProgress(getString(R.string.firmware_update_info));
                    break;

            }
        }
    };

    private void showProgress(String str) {

        if (mProgressDialog == null)
            mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
        //mpDialog.setTitle("提示");//设置标题
        mProgressDialog.setMessage(str);
        mProgressDialog.setIndeterminate(false);//设置进度条是否为不明确

        mProgressDialog.setCancelable(false);//设置进度条是否可以按退回键取消

        //设置点击进度对话框外的区域对话框不消失
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
    }

    /**
     * 是否下载dialog
     */
    private void showIsUpdateDialog(final String url_str, final String file_name, final String file_size, final String file_md5) {

        updateDialog = new OneDialog(MainActivity.this, getString(R.string.firmware_finding), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查看
                api.downloadSoft(MainActivity.this, url_str, file_name, file_size, file_md5);
                updateDialog.dismiss();
                showProgress(getString(R.string.firmware_downloading));
            }
        });
        updateDialog.show();
    }

    public void displayDragOrZoomoutIn() {
        mZoomOut_fill.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSdcardStatue(boolean statue) {
        if (!statue) {
            if (mTabs.get(0) instanceof IndexFragment) {
                ((IndexFragment) (mTabs.get(0))).displayNoSdcard();
            }
        }
    }

    public void showWaitDialog() {
        showProcessDialog();
    }

    public void hideWaitDialog() {
        hideProgressDialog();
    }
}
